﻿

using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.DAL;
using Gift.Model;

    public partial class admin_order_orders : BaseAdmin
    {
        readonly DALOrderCompain theOrderCompain = new DALOrderCompain();
        readonly DALCompain theCompain = new DALCompain();
        // Fields
        public string cardprice = "0";
        public string shopprice = "0";
        public string carmsg = "";
        public string scoreprice = "0";
        public string sumprice = "0";

        public string remainprice = "0";

        // Methods
        private void Bind()
        {
            string sql = "select orderid, ordercode, memberid, (select memberlogin from DB_Member where memberid=DB_order.memberid) as memberlogin, pay, ship, cname, tel, phone, post, address, email, [content], cname1, tel1, phone1, post1, address1, email1, content1, states, "
                     + " ordertime, paytime, shiptime, languages, totalprice, cardprice, scoreprice, orderscore, cardid, scoretype, SendCompany, SendCode, convert(varchar(10),senddate,111) as senddate, senddate1,shopprice "
                    + "  from DB_order where orderid=" + base.Request.QueryString["oid"].ToString() + "";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                this.ordercode.Text = table.Rows[0]["ordercode"].ToString();
                this.shopprice = table.Rows[0]["shopprice"].ToString() == "" ? "0" : table.Rows[0]["shopprice"].ToString();

        
                    DataTable dtCards = new DataTable();
                    dtCards = SQLAccess.GreatDs("select c.* from DB_Order o join tbOrderAccount oa "
                                                 + " on o.OrderCode = oa.OrderCode "
                                                 + " join DB_Card c on oa.cardid = c.cardid "
                                                 + " where o.ordercode='" + this.ordercode.Text + "'").Tables[0];
                    int iRow = 0;
                    foreach (DataRow drCard in dtCards.Rows)
                    {
                        iRow++;
                        if (iRow % 5 == 0)
                        {
                            this.lblCardCode.Text += drCard["cardcode"].ToString() + "|\n";
                        }
                        else
                        {
                            this.lblCardCode.Text += drCard["cardcode"].ToString() + "|";
                        }
                    }
                    if (shopprice.ToString() != "0")
                    {
                        this.lblCardCode.Text = this.lblCardCode.Text + "\n 账户支付:" + shopprice.ToString() + ";";
                    }

                this.memberid.Text = table.Rows[0]["cname"].ToString();
                this.states1.Value = table.Rows[0]["states"].ToString();
                this.contents.Text = table.Rows[0]["content1"].ToString();
                string str2 = "select * from DB_Pay where payid in (" + table.Rows[0]["pay"].ToString() + ")";
                DataTable table2 = new DataTable();
                table2 = SQLAccess.GreatDs(str2).Tables[0];

                this.pay.Text = "";
                foreach (DataRow dr in table2.Rows)
                {
                    this.pay.Text = this.pay.Text != "" ? this.pay.Text + ";" + dr["payname"].ToString() : dr["payname"].ToString();
                }

 
                this.orderno.Text = table.Rows[0]["content"].ToString();
                if (table.Rows[0]["states"].ToString() == "0")
                {
                    this.states.Text = "新订单";
                    if (base.Request.QueryString["flag"] == "1")
                    {
                        this.txtAddress.ReadOnly = false;
                        this.txtCname.ReadOnly = false;

                        this.txtPhone.ReadOnly = false;
                        this.txtTel.ReadOnly = false;
                        this.btnUpdateAddress.Enabled = true;
                    }
                    else
                    {
                        this.txtAddress.ReadOnly = true;
                        this.txtCname.ReadOnly = true;
                        this.txtPhone.ReadOnly = true;
                        this.txtTel.ReadOnly = true;
                        this.btnUpdateAddress.Enabled = false;
                    }
                }
                else
                {
                    this.txtAddress.ReadOnly = true;
                    this.txtCname.ReadOnly = true;

                    this.txtPhone.ReadOnly = true;
                    this.txtTel.ReadOnly = true;
                    this.btnUpdateAddress.Enabled = false;
                }
                if (table.Rows[0]["states"].ToString() == "0")
                {
                    this.states.Text = "新订单";
                }
                else if (table.Rows[0]["states"].ToString() == "1")
                {
                    this.states.Text = "备货中";
                }
                else if (table.Rows[0]["states"].ToString() == "2")
                {
                    this.states.Text = "已发货";
                }
                else if (table.Rows[0]["states"].ToString() == "3")
                {
                    this.states.Text = "已完成";
                }
                else if (table.Rows[0]["states"].ToString() == "5")
                {
                    this.states.Text = "已取消";
                }
                this.ordertime.Text = table.Rows[0]["ordertime"].ToString();
                this.txtCname.Text = table.Rows[0]["cname1"].ToString();
                this.txtAddress.Text = table.Rows[0]["address1"].ToString();
                this.txtTel.Text = table.Rows[0]["tel1"].ToString();
                this.txtSendTime.Value = table.Rows[0]["sendDate"].ToString();
              // this.post.Text = table.Rows[0]["post1"].ToString();
                this.txtPhone.Text = table.Rows[0]["phone1"].ToString();
                this.cardprice = table.Rows[0]["cardprice"].ToString();
                DataTable table5 = SQLAccess.GreatDs("select sum(DB_Car.pronum) as pronum,DB_Car.price,sum(DB_Car.sumprice ) as sumprice,DB_Car.contents,DB_Shoppro.typeid,DB_Shoppro.proname,DB_Shoppro.saleprice,DB_Shoppro.prosmallpic,DB_Shoppro.proid   "
                         + " from DB_Car inner join DB_Shoppro on DB_Car.productid=DB_Shoppro.proid " 
                         + " where DB_Car.flag=1 and DB_Car.orderid=" + table.Rows[0]["orderid"].ToString()
                         + " group by DB_Car.pronum,DB_Car.price,DB_Car.sumprice,DB_Car.contents,DB_Shoppro.typeid,DB_Shoppro.proname,DB_Shoppro.saleprice,DB_Shoppro.prosmallpic,DB_Shoppro.proid ").Tables[0];
                if (table5.Rows.Count > 0)
                {
                    foreach (DataRow row in table5.Rows)
                    {
                        this.sumprice = string.Format("{0:f}", Convert.ToSingle(this.sumprice) + Convert.ToSingle(row["sumprice"]));
                        this.carmsg = this.carmsg + "<tr bgcolor='#ffffff'>";
                        string carmsg = this.carmsg;
                        this.carmsg = carmsg + "<td width='25%' align='center'><a href='/cn/products_details.aspx?tid=" + row["typeid"].ToString() + "&pid=" + row["proid"].ToString() + "' target=_blank><img src='/uploadfile/product/" + row["prosmallpic"].ToString() + "' align='middle' border='0' /></a></td> ";
                        string str7 = this.carmsg;
                        this.carmsg = str7 + "<td><font style='FONT-WEIGHT: bold' color='#339900'>" + row["proname"].ToString() + "</font>&nbsp;<br/>" + row["contents"].ToString() + "</td>";
                        this.carmsg = this.carmsg + "<td width='20%' align='middle'>" + string.Format("{0:f}", row["price"]) + " 元</td>";
                        this.carmsg = this.carmsg + "<td width='10%' align='middle'>" + row["pronum"].ToString() + "</td>";
                        this.carmsg = this.carmsg + "<td width='20%' align='middle'>" + string.Format("{0:f}", row["sumprice"]) + "元</td>";
                        this.carmsg = this.carmsg + "</tr>";
                    }
                }
                this.remainprice = string.Format("{0:f}", (Convert.ToSingle(this.sumprice) - Convert.ToSingle(this.cardprice) - Convert.ToSingle(this.shopprice)));
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if ((this.states1.Value.ToString() == "1") || (this.states1.Value.ToString() == "2"))
            {
                DataTable table = SQLAccess.GreatDs("select memberid,ordercode,orderscore,scoreprice,scoretype from DB_Order where orderid=" + base.Request.QueryString["oid"] + "").Tables[0];
                if ((table.Rows.Count > 0) && (table.Rows[0]["scoretype"].ToString() == "0"))
                {
                    SQLAccess.DoSql(string.Concat(new object[] { "Update DB_Member set score1=score1+", Convert.ToInt32(table.Rows[0]["orderscore"]) - Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score2=score2-", Convert.ToInt32(table.Rows[0]["scoreprice"]), ",score3=score3+", Convert.ToInt32(table.Rows[0]["orderscore"]), " where memberid=", table.Rows[0][0].ToString(), "" }));
                    SQLAccess.DoSql(string.Concat(new object[] { "insert into DB_Score (memberid,scorename,scoreprice,content,updatetime,scoretype) values (", table.Rows[0][0].ToString(), ",'订单赠积分：", table.Rows[0]["ordercode"], "','+", table.Rows[0]["orderscore"], "','赠积分：", table.Rows[0]["orderscore"], "','", DateTime.Now, "',0)" }));
                }
            }
            SQLAccess.DoSql("update DB_Order set states=" + this.states1.Value + ",content1='" + re.replace(this.contents.Text) + "',scoretype=1 where orderid=" + base.Request.QueryString["oid"] + "");
            base.Response.Write("<script language=javascript>alert('操作成功!');window.location.href='order_process.aspx';</script>");
            base.Response.End();
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select * from DB_order where orderid<" + base.Request.QueryString["oid"] + " order by orderid desc";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                base.Response.Redirect("orders.aspx?oid=" + table.Rows[0]["orderid"].ToString() + "");
                base.Response.End();
            }
            else
            {
                base.Response.Redirect("orders.aspx?oid=" + base.Request.QueryString["oid"] + "");
                base.Response.End();
            }
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select * from DB_order where orderid>" + base.Request.QueryString["oid"] + " order by orderid asc";
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            if (table.Rows.Count > 0)
            {
                base.Response.Redirect("orders.aspx?oid=" + table.Rows[0]["orderid"].ToString() + "");
                base.Response.End();
            }
            else
            {
                base.Response.Redirect("orders.aspx?oid=" + base.Request.QueryString["oid"] + "");
                base.Response.End();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!base.IsPostBack && (base.Request.QueryString["oid"] != ""))
            {
                this.Bind();
                this.BindCompainTypeList();
                this.BindCompain();
                if (base.Request.QueryString["flag"] == "1")
                {
                    this.tbOperate.Visible = true;
                    this.tblCompain.Visible = false;
                }
                else if (base.Request.QueryString["flag"] == "2")
                {
                    this.tbOperate.Visible = false;
                    this.tblCompain.Visible = true;
                }
                else
                {
                    this.tbOperate.Visible = false;
                    this.tblCompain.Visible = false;
                }
            }
        }

        void BindCompainTypeList()
        {
            DataSet ds;
            ds = theCompain.GetList("");
            if (ds != null && ds.Tables.Count > 0)
            {
                this.ddlCompainType.DataTextField = "CompainName";
                this.ddlCompainType.DataValueField = "CompainId";
                this.ddlCompainType.DataSource = ds.Tables[0].DefaultView;
                this.ddlCompainType.DataBind();
                this.ddlCompainType.Items.Insert(0, new ListItem("投诉类别...", "0"));
            }

            dbOrder oOrder;
            oOrder = new Order().GetModel(Convert.ToInt64(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);
            if (oOrderCompain != null)
            {
                this.ddlCompainType.Items.FindByValue(oOrderCompain.CompainId.ToString()).Selected = true;
                this.txtCompain.Text = oOrderCompain.Content;
            }
        }

        protected void btnCompain_Click(object sender, EventArgs e)
        {
            if (this.txtCompain.Text.Trim() == "")
            {
                Response.Write("<script>alert('投诉内容不能为空!')</script>");
                return;
            }
              dbOrder oOrder;
            oOrder = new Order().GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);
           
            if (oOrderCompain == null)
            {
                oOrderCompain = new tbOrderCompain();
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.AddDate = DateTime.Now;
                theOrderCompain.Add(oOrderCompain);
            }
            else
            {
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.AddDate = DateTime.Now;
                theOrderCompain.Update(oOrderCompain);
            }

        }

        private void BindCompain()
        {
            dbOrder oOrder;
            oOrder = new Order().GetModel(Convert.ToInt64(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);
            if (oOrderCompain != null)
            {
                this.ddlCompainType.Items.FindByValue(oOrderCompain.CompainId.ToString()).Selected = true;
                this.txtCompain.Text = oOrderCompain.Content;
                this.txtProcess.Text = oOrderCompain.Process;
            }
        }

        protected void btnProcess_Click(object sender, EventArgs e)
        {
            dbOrder oOrder;
            oOrder = new Order().GetModel(int.Parse(base.Request.QueryString["oid"]));
            tbOrderCompain oOrderCompain;
            oOrderCompain = theOrderCompain.GetModelByOrderCode(oOrder.ordercode);
            if (this.txtProcess.Text.Trim() == "")
            {
                Response.Write("<script>alert('处理结果不能为空!')</script>");
                return;
            }
            if (oOrderCompain == null)
            {
                oOrderCompain = new tbOrderCompain();
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.Process = this.txtProcess.Text.Trim();
                oOrderCompain.ProcessDate = DateTime.Now;
                theOrderCompain.Add(oOrderCompain);
            }
            else
            {
                oOrderCompain.CompainId = int.Parse(this.ddlCompainType.SelectedItem.Value);
                oOrderCompain.Content = this.txtCompain.Text.Trim();
                oOrderCompain.OrderCode = oOrder.ordercode;
                oOrderCompain.Process = this.txtProcess.Text.Trim();
                oOrderCompain.ProcessDate = DateTime.Now;
                theOrderCompain.Update(oOrderCompain);
            }

            Response.Write("<script>alert('保存成功!')</script>");
            return;
        }

        protected void btnUpdateAddress_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime.Parse(this.txtSendTime.Value);
            }
            catch
            {
                Response.Write("<script>alert('送货日期格式不正确!')</script>");
                return; 
            }
            string strSql = "update DB_Order set address1='" + this.txtAddress.Text.Trim() +"'"
                           + ", cname1='" + this.txtCname.Text.Trim() +"'"
                           + ", sendDate='" + this.txtSendTime.Value.Trim() + "'"
                           + ", tel1='" + this.txtTel.Text.Trim() + "'"
                           + ", phone1='" + this.txtPhone.Text.Trim() + "'"                  
                           + " where orderid=" + base.Request.QueryString["oid"].ToString() + "";
            SQLAccess.DoSql(strSql);

            Response.Write("<script>alert('更新成功!')</script>");
            return;
        }

    }
